#include "fileops.h"
#include <stdio.h>
#include <string.h>

int readCoursesFromFile(Course courses[], int *numCourses) {
    FILE *fp = fopen("courses.txt", "r");
    if (!fp) {
        printf("打开文件失败！\n");
        return -1;
    }

    int count = 0;
    while (fscanf(fp, "%[^,],%[^,],%[^,],%[^,],%[^\n]\n",
                  courses[count].courseID,
                  courses[count].courseName,
                  courses[count].teacherName,
                  courses[count].courseTime,
                  courses[count].courseLocation) != EOF && count < MAX_COURSES) {
        count++;
    }

    *numCourses = count;
    fclose(fp);
    return 0;
}

int saveCoursesToFile(Course courses[], int numCourses) {
    FILE *fp = fopen("courses.txt", "w");
    if (!fp) {
        printf("打开文件失败！\n");
        return -1;
    }

    for (int i = 0; i < numCourses; i++) {
        fprintf(fp, "%s,%s,%s,%s,%s\n",
                courses[i].courseID,
                courses[i].courseName,
                courses[i].teacherName,
                courses[i].courseTime,
                courses[i].courseLocation);
    }

    fclose(fp);
    return 0;
}
